var SiteMap = SiteMap || {};

// Team Projects  
SiteMap.Projects = {
	Folders: {
		'product-listing-ads': { 'id': '0Bxm7KG10dy1ZY2UzSmdSZlhhdW8', 'title': 'Product Listing Ads', 'url': 'partials/product-listing-ads.html', 'template': 'B' },
  		'shopping-property':   { 'id': '0Bxm7KG10dy1ZTkU4WUgwOFdHZDQ', 'title': 'Shopping Property', 'url': 'partials/shopping-property.html', 'template': 'A' },
  		'google-express':      { 'id': '0Bxm7KG10dy1ZUmkyV0d6V1ZNcmc', 'title': 'Google Express', 'url': 'partials/google-express.html', 'template': 'B' },
  		'trust':               { 'id': '0Bxm7KG10dy1ZNmZ4VVdnQzlnVkU', 'title': 'Trust', 'url': 'partials/trust.html', 'template': 'A' },
  		'merchant-tools':      { 'id': '0Bxm7KG10dy1ZMVdIci16cUh1TXc', 'title': 'Merchant Tools', 'url': 'partials/merchant-tools.html', 'template': 'A' },  
  		'more':                { 'id': '0Bxm7KG10dy1ZbHNYTWxDQWplVzQ', 'title': 'More...', 'url': 'partials/more.html', 'template': 'A' }
	}
};

// router to load subpage within the right project context
SiteMap.Projects.Router = {
	prevHashTokens: [],
	currHashTokens: [],
	
	init: function() {	
		hasher.changed.add(SiteMap.Projects.Router.handle);
		hasher.initialized.add(SiteMap.Projects.Router.handle);
		hasher.init();
	},
	
	handle: function(newHash, oldHash) {			
		if (oldHash != undefined && oldHash != "") {
			this.prevHashTokens = oldHash.split("\/");
			if (this.prevHashTokens.length == 1) {
				this.prevHashTokens[1] == "";
			}
		} else {
			this.prevHashTokens = ["", ""];
		}
		
		if (newHash != undefined && newHash != "") {
			this.currHashTokens = newHash.split("\/");
			if (this.currHashTokens.length == 1) {
				this.currHashTokens[1] = "";
			}
		} else {
			hasher.setHash("product-listing-ads");
			this.currHashTokens = ["product-listing-ads", ""];
		}
		
		if (this.prevHashTokens[0] == "" && this.currHashTokens[1] == "") {
			// loading first time default page
			SiteMap.Projects.SubPage.init(this.currHashTokens[0]); 
		} else if (this.prevHashTokens[0] == "" && this.currHashTokens[1] !== "") {
			// loading first time, but with document
			SiteMap.Projects.SubPage.init(this.currHashTokens[0], this.currHashTokens[1]);
		} else if (this.prevHashTokens[0] !== "" && this.prevHashTokens[0] == this.currHashTokens[0]) {
			 // if second token is missing, then load default only, otherwise load word doc
			if (this.prevHashTokens[1] !== this.currHashTokens[1] && this.currHashTokens[1] !== "") {
				SiteMap.Projects.SubPage.getDocument(this.currHashTokens[1]);
			} else {
				SiteMap.Projects.SubPage.getDefault();
			}
		} else {
			// reload entire thing
			SiteMap.Projects.SubPage.init(this.currHashTokens[0], this.currHashTokens[1]);
		}
	}
};

// Projects Sub Page
/* https://script.google.com/a/google.com/d/1DnmAprpUppnTkWxdLhm0ocqpvpmq-SRIsKnmo-4TYYxaCKehF5lnr5Db/edit?usp=drive_web */
SiteMap.Projects.SubPage = {
	speed: 0.200,	
	folder: null,	
	loader: {
		menu:     "https://script.google.com/a/macros/google.com/s/AKfycbzfV9bl6xYkYdjCpjE4AleWUbKNkEMWS71Vjp57bTDRwCaq7wcd/exec",
		deepmenu: "https://script.google.com/a/macros/google.com/s/AKfycby26fCNNRHhxFzdkY9aSy-8uZanTz6iA_xtii4XDSsLz7VyFNW2/exec",
		doc:      "https://script.google.com/a/macros/google.com/s/AKfycbyjg1kwv70q3Kkq5sAnSpGCGX2SIOc2tRlXSfq82b4O1oPuuc4/exec"
	},
	
	isMenuLoaded: false,
	isDocumentLoaded: false,
	isDocLoading: false,	
	currDocId: null,
	
	init: function(id, docId) {
		console.log('initialize sub page >>>');
		this.id = id || 'product-listing-ads';
		this.currDocId  = (docId != undefined) ? docId : null;
		
		if (id in SiteMap.Projects.Folders) {
			this.folder = SiteMap.Projects.Folders[id];
		}
		
		this.elmLoader   = $('#loader');
		this.elmTitle    = $('#subpage-title'); 
		this.elmMenu     = $('#subpage-menu');
		this.elmContent  = $('#subpage-content');
		this.elmDocument = $('#document');
		
		this.observe();		
		this.getMenu();
	},
	
	observe: function() {
		console.log('observe >>>');
		// load menu first but don't show
		console.log('- subpageMenuLoaded');
		$(this.elmMenu).on('subpageMenuLoaded', function(e) {
			SiteMap.Projects.SubPage.isMenuLoaded = true;
			SiteMap.Projects.SubPage.observeMenu();
			SiteMap.Projects.SubPage.activeItem(SiteMap.Projects.SubPage.currDocId);			
			if (SiteMap.Projects.SubPage.currDocId) {
				SiteMap.Projects.SubPage.getDocument(SiteMap.Projects.SubPage.currDocId);
			} else {
				SiteMap.Projects.SubPage.getDefault();
			}

			if (SiteMap.Projects.SubPage.isDocumentLoaded && SiteMap.Projects.SubPage.isMenuLoaded) {
				SiteMap.Projects.SubPage.display();
			}
		});
		
		console.log('- subpageDeepMenuLoaded');
		$(this.elmMenu).on('subpageDeepMenuLoaded', function(e){
			SiteMap.Projects.SubPage.isMenuLoaded = true;			
			SiteMap.Projects.SubPage.observeDeepMenu();
			SiteMap.Projects.SubPage.activeItem(SiteMap.Projects.SubPage.currDocId);
			if (SiteMap.Projects.SubPage.currDocId) {
				SiteMap.Projects.SubPage.getDocument(SiteMap.Projects.SubPage.currDocId);
			} else {
				SiteMap.Projects.SubPage.getDefault();
			}
			
			if (SiteMap.Projects.SubPage.isDocumentLoaded && SiteMap.Projects.SubPage.isMenuLoaded) {
				SiteMap.Projects.SubPage.display();
			}

			//if (SiteMap.SubPage.anchor) {
			//	SiteMap.Research.SubPage.scrollTo(SiteMap.Research.SubPage.anchor);
			//}
		});
		
		// load document first, but don't show
		console.log('- subpageDocumentLoaded');
		$(this.elmContent).on('subpageDocumentLoaded', function(e) {
			SiteMap.Projects.SubPage.isDocumentLoaded = true;
			if (SiteMap.Projects.SubPage.isDocumentLoaded && SiteMap.Projects.SubPage.isMenuLoaded) {
				SiteMap.Projects.SubPage.display();
			}
		});
	},
	
	// accordion and anchor programming
	observeDeepMenu: function() {
		console.log('observe deep menu >>>');
		$('#subpage-menu > ul > li.has-sub > span').click(function(e) { 
			e.preventDefault();
			console.log('click to expand menu');
			
			//var anchor = $(this).parent().attr('data-scroll');
			$('#subpage-menu li.has-sub').removeClass('active');
			$(this).closest('li').addClass('active');
				
			var checkElement = $(this).next();
			if((checkElement.is('ul')) && (checkElement.is(':visible'))) {
				$(this).closest('li').removeClass('active');
				checkElement.slideUp('normal');
			}
			if((checkElement.is('ul')) && (!checkElement.is(':visible'))) {
				$('#subpage-menu ul ul:visible').slideUp('normal');
				checkElement.slideDown('normal');
				//hasher.setHash(anchor);
			}
			if($(this).closest('li').find('ul').children().length == 0) {
				return true;
			} else {
				return false;	
			}		
		});
		
		
		$('#subpage-menu li.has-sub ul > li').fastClick(function(e){
			if (!SiteMap.Projects.SubPage.isDocLoading) {
				SiteMap.Projects.SubPage.isDocLoading = true;
				SiteMap.Projects.SubPage.appendLoader();
				
				$('#docmenu li').removeClass('active');
				$(this).addClass('active');
				
				this.currDocId = $(this).attr('data-load');
				var newHash = SiteMap.Projects.SubPage.id + "/" + this.currDocId;
				hasher.setHash(newHash);
			}
		});
		
	},
	
	// display all content simultaneously
	display: function() {
		console.log('- display menu and content');
		$(this.elmMenu).css('display','block');
		$(this.elmContent).css('display','block');				
		TweenMax.to([$(this.elmMenu), $(this.elmContent)], this.speed, { opacity: 1, ease: Sine.easeInOut, onComplete: function() {
			SiteMap.Projects.SubPage.removeLoader();
			SiteMap.Projects.SubPage.isDocLoading = false;
		} });
	},
	
	// append document loader
	appendLoader: function() {
		console.log('appending loader >>>');
		var html = '<div class="subpage-loader" id="subpage-loader"><div class="content"><article><img src="../img/general/loader-subpage.gif" width="32" height="32" alt="Loading..."></article></div></div>';
		$(this.elmContent).parent().append(html);
	},
	
	// remove document loader
	removeLoader: function() {
		console.log('removing loader >>>');
		
		if ($('#loader')) {
			TweenMax.to($('#loader'), this.speed, { opacity: 0, onComplete: function(){
				$('#loader').remove();
			} });
		}
		
		if ($('#subpage-loader')) {
			TweenMax.to($('#subpage-loader'), this.speed, { opacity: 0, onComplete: function(){
				$('#subpage-loader').remove();
			} });
		}	
	},
	
	getDefault: function() {
		console.log('loading default content >>> ' + this.folder.url);
		$(this.elmDocument).load(this.folder.url);
		$('#docmenu li').removeClass('active');
		$(this.elmContent).trigger('subpageDocumentLoaded');
	},
	
	getMenu: function() {
		console.log('fetching menu via drive script >>>');
		if (this.folder.template === 'A') {
			// single level menu
			console.log('default one level menu is loading >>>');
			var URL = this.loader.menu + "?id=" + this.folder.id + "&prefix=SiteMap.Projects.SubPage.loadMenu";		
			$.ajax({ url: URL, dataType: 'jsonp' });
		} else {
			// two level menu	
			console.log('multilevel menu is loading >>>');		
			var URL = this.loader.deepmenu + "?id=" + this.folder.id + "&prefix=SiteMap.Projects.SubPage.loadDeepMenu";		
			$.ajax({ url: URL, dataType: 'jsonp' });	
		}
	},
	
	loadMenu: function(response){
		console.log('loading default menu >>>');
		var menu = response.menu;
		menu.sort(function(a, b){
		    if (a.name < b.name) return -1;
		    if (a.name > b.name) return 1;
		    return 0;	
		});
		
		var html = '<ul class="docmenu" id="docmenu">';
		for (var i = 0, len = menu.length; i < len; i++) {
			var item = menu[i];
			html += '<li data-load="'+item.id+'">'+ item.name +'</li>';
		}
		html += "</ul>";
		
		$(this.elmTitle).html(response.name);
		$(this.elmMenu).html(html);
		$(this.elmContent).parent().css('min-height',$(this.elmMenu).height() + 'px'); 
		$(this.elmMenu).trigger("subpageMenuLoaded");
		//this.activeItem(this.currDocId);
	},
	
	loadDeepMenu: function(response) {
		console.log('loading multi-level menu >>>');
		var folders  = response.folders;
		var html = '<ul class="docmenu" id="docmenu">';	
		for (var i = 0, len = folders.length; i < len; i++) {			
			var folder = folders[i];
			html += '<li class="has-sub" data-folder="'+folder.id+'"><span>' + folder.name + '</span>';
			html += '<ul style="display:none;">';
			
			// sort menu alphabetically
			var menu = folder["docs"];
			menu.sort(function(a, b){
		    	if (a.name < b.name) return -1;
		    	if (a.name > b.name) return 1;
		    	return 0;	
			});
			
			for (var j = 0, len2 = menu.length; j < len2; j++) {
				html += '<li data-load="'+ menu[j].id+'"><span>' + menu[j].name + '</span></li>';
			}
			html += '</ul>';
			html += '</li>';
		}
		html += '</ul>';	
		
		$(this.elmTitle).html(response.name);
		$(this.elmMenu).html(html);
		$(this.elmContent).parent().css('min-height',$(this.elmMenu).height() + 'px'); 
		$(this.elmMenu).trigger("subpageDeepMenuLoaded");
		//this.activeItem(this.currDocId);
	},
	
	activeItem: function() {
		console.log('activate item of the menu >>>');
		console.log('- current doc Id: ' + this.currDocId);
		if (this.currDocId) {
			$('#docmenu li').removeClass('active');
			var element = $('#docmenu li[data-load="'+this.currDocId+'"]');
			if (element) {
				$(element).addClass('active');
				if (this.folder.template == 'B') {
					// open the thing
					$(element).parent().slideDown('normal');
					$(element).parent().parent().addClass('active');
				}
			}
		}
	},
	
	observeMenu: function() {
		console.log('observing menu >>>');
		$('#docmenu li').fastClick(function(){
			if (!SiteMap.Projects.SubPage.isDocLoading) {
				SiteMap.Projects.SubPage.isDocLoading = true;
				SiteMap.Projects.SubPage.appendLoader();
				
				$('#docmenu li').removeClass('active');
				$(this).addClass('active');
				
				this.currDocId = $(this).attr('data-load');
				var newHash = SiteMap.Projects.SubPage.id + "/" + this.currDocId;
				hasher.setHash(newHash);
			}
		});
	},
	
	getDocument: function(docId) {
		console.log('loading document >>>');
		TweenMax.to($(this.elmContent), this.speed, { opacity: 0, ease: Sine.easeInOut, onComplete: function(){
			$(this).css('display','none');
		} });
		
		var URL = this.loader.doc + "?id=" + docId + "&prefix=SiteMap.Projects.SubPage.loadDocument";
		$.ajax({ url: URL, dataType: 'jsonp' });
	},
	
	// http://www.cloudtouch.co.uk/2012/03/04/an-introduction-to-google-apps-script-part-2-send-emails-using-spreadsheets-gmail-and-a-document-template/
	loadDocument: function(response) {
		console.log(response);
		var title = '<h2 id="document-title" class="document-title">'+response.name+'</h2>';
		
		var styleData = response.content
			.replace('<style','<style id="docstyle"')
			.replace(/}\s?p\s?{.*}/,'}')
			.replace('h2\s?{.*}','')
			.replace('h3\s?{.*}','')
			.replace('h4\s?{.*}','')
			.replace('h5\s?{.*}','')
			.replace('h6\s?{.*}','')
			.replace(/\.title\s?{.*}/,'')
			.replace(/\.subtitle\s?{.*}/,'')
			.replace(/@import url\(\'.*\'\);/g,'')
			.replace(/\.c/g,'#document .c')
			.replace('ol','#document ol')
			.replace('ul','#document ul')
			.replace(/font-size:(\d{1,2})pt(;{0,1})/g,"")
		; 
		var style    = $(styleData).filter('#docstyle');		
		var bodyData = response.content.replace('<body', '<body><div id="body"').replace('</body>','</div></body>');
		var body     = $(bodyData).filter('#body');
		
		var tags2strip = ['p','h1','h2','h3','b','hr'];
		for (var i = 0, len = tags2strip.length; i < len; i++) {
			$(body).find(tags2strip[i]).each(function(){
				$(this).attr('class','');
			});
		}
		
		var content = title + '<style>' + $(style).html() + '</style>' + $(body).html();
		$(this.elmDocument).html(content);
		$(this.elmContent).trigger('subpageDocumentLoaded');
	}
};


// On Document ready, initialize routing system & the rest
$(document).ready(function(){
	SiteMap.Projects.Router.init();	
});